package org.example.mallchat.common.intecepter;

import cn.hutool.core.util.ObjectUtil;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.example.mallchat.cache.UserBlackCacheHandler;
import org.example.mallchat.common.domain.local.RequestInfo;
import org.example.mallchat.common.thread.ThreadLocalHandler;
import org.example.mallchat.domain.enums.BlackEnum;
import org.example.mallchat.service.LoginService;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;

/**
 * @author: zzh
 * @date: 2024/12/22 16:20:36
 * @version: 1.0
 */
@Order(2)
@Component//Spring的拦截器，黑名单校验用户
public class BlackIntercepter implements HandlerInterceptor {
    @Resource
    private UserBlackCacheHandler userBlackCacheHandler;

    @Override
    public boolean preHandle(HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {
        // 获取该用户的信息
        RequestInfo requestInfo = ThreadLocalHandler.getRequestInfo();
        String uid = requestInfo.getUid();
        if (ObjectUtil.isEmpty(uid)){
            return false;// 都没有uid，直接返回false
        }
        // 查询该用户是否存在黑名单中
        // 黑名单缓存获取 (所有的) uid -> target 、 ip -> target 、 device -> target
        Map<Integer, Set<String>> blackMap = userBlackCacheHandler.getUidToBlackMap();
        if (ObjectUtil.isEmpty(blackMap)){// 黑名单缓存为空，直接返回true
            return true;
        }
        if (ObjectUtil.isNotNull(blackMap.get(BlackEnum.UID.getId())) && blackMap.get(BlackEnum.UID.getId()).contains(uid)) {
            // 黑名单用户，返回403
            response.sendError(403, "您已被拉黑，请联系客服");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().println("");
            return false;
        }
        // 判断ip是否在黑名单中
        String ip = requestInfo.getIp();
        if (StringUtils.isBlank(ip)){
            return true;
        }
        if (ObjectUtil.isNotNull(blackMap.get(BlackEnum.IP.getId())) &&  blackMap.get(BlackEnum.IP.getId()).contains(ip)) {
            // 黑名单ip，返回403
            response.sendError(403, "您已被拉黑，请联系客服");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().println("");
            return false;
        }
        // todo 判断设备是否在黑名单中
        return true;
    }

}
